package com.fliad.ai.service;

import com.fliad.ai.entity.AiLlm;
import org.noear.solon.annotation.Component;
import org.noear.wood.DbContext;
import org.noear.wood.annotation.Db;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

@Component
public class AiLlmService {

    @Db
    DbContext db;

    public boolean create(AiLlm llm) throws SQLException {
        llm.setCreated(new Date());
        llm.setModified(new Date());
        return db.table("ai_llm")
                .setEntity(llm)
                .insert() > 0;
    }

    public AiLlm get(Long id) throws SQLException {
        return db.table("ai_llm")
                .whereEq("id", id)
                .selectItem("*", AiLlm.class);
    }

    public List<AiLlm> list(String title, String dialect, Boolean supportChat, Boolean supportEmbed) throws SQLException {
        return db.table("ai_llm")
                .where(buildQueryCondition(title, dialect, supportChat, supportEmbed))
                .orderBy("id DESC")
                .selectList("*", AiLlm.class);
    }

    // 新增方法：构建查询条件
    private String buildQueryCondition(String title, String dialect, Boolean supportChat, Boolean supportEmbed) {
        StringBuilder condition = new StringBuilder("1=1");
        if (title != null && !title.isEmpty()) {
            condition.append(" AND title LIKE '%").append(title).append("%'");
        }
        if (dialect != null && !dialect.isEmpty()) {
            condition.append(" AND dialect = '").append(dialect).append("'");
        }
        if (supportChat != null) {
            condition.append(" AND support_chat = ").append(supportChat);
        }
        if (supportEmbed != null) {
            condition.append(" AND support_embed = ").append(supportEmbed);
        }
        return condition.toString();
    }

    public boolean update(Long id, AiLlm llm) throws SQLException {
        llm.setModified(new Date());
        return db.table("ai_llm")
                .whereEq("id", id)
                .setEntity(llm)
                .update() > 0;
    }

    public boolean delete(Long id) throws SQLException {
        return db.table("ai_llm")
                .whereEq("id", id)
                .delete() > 0;
    }
}